package com.nlscan.qdkit.common.core.app

import android.app.Activity
import android.app.Application
import android.content.Context
import android.util.Log
import com.dreamlive.cn.clog.CollectLog
import com.nlscan.qdkit.common.core.BuildConfig
import com.nlscan.qdkit.common.core.R
import com.nlscan.qdkit.common.core.ext.logI
import com.nlscan.qdkit.common.core.model.entity.ApplicationInfo
import com.quvii.qvlib.QvLibCore
import com.quvii.qvlib.base.QvBaseApp
import com.quvii.qvlib.helper.QvAppReportHelper
import com.quvii.qvlib.util.QvEncryptKeyStoreUtil
import com.quvii.qvlib.util.QvPermissionUtils
import com.quvii.qvlib.util.QvWifiUtil
import com.tencent.bugly.crashreport.CrashReport
import com.airbnb.mvrx.Mavericks

/**
 *
 * -- 提供外部调用，不改为 BaseApp
 */
abstract class App : QvBaseApp() {
    abstract fun getAppInfo(): ApplicationInfo
    abstract fun getAppReportInfo(): String

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
//        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        //日志打印工具类初始化优先级最高
        QvEncryptKeyStoreUtil.initKeyStore()

        // Initialize Mavericks
        Mavericks.initialize(this)

        val info = getAppInfo()
        QvAppReportHelper.getInstance().initLogUtil(info.logDebug) { getAppReportInfo() }
        if (info.logDebug) {
            logI(getAppReportInfo())
        }

        // TODO: 路径改为外部传入

        //init crash log
        val crashLogPath = getExternalFilesDir("").toString() + "/log/crash/"
        CollectLog.getInstance()
            .init(this, crashLogPath)

        //init bugly
        // TODO: 要改为外层传入
        val debugEnable = BuildConfig.DEBUG
        Log.d("TAG41", "TAG BUGLY debugenable: $debugEnable")
        CrashReport.initCrashReport(applicationContext, "3a37831233", debugEnable)


//        RouterCenter.init(this)

        initQvLib()
    }

    override fun onActivityStarted(p0: Activity?) {

    }

    override fun onActivityStopped(p0: Activity?) {

    }

    private fun initQvLib() {
        QvWifiUtil.getInstance().init(this)
        QvLibCore.getInstance().init(getAppInfo().applicationId)

        QvPermissionUtils.init(
            R.string.key_permission_title_permission_failed,
            R.string.key_permission_message_permission_failed,
            R.string.key_permission_resume,
            R.string.key_cancel,
            R.string.key_setting
        )
    }

    fun getApplicationId() = getAppInfo().applicationId

    companion object {
        fun getContext(): Application {
            return getInstance()
        }

        fun getInstance(): App {
            return (QvBaseApp.getInstance() as? App)!!
        }
    }
}